package network.server;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;

public class RoomsPool {

    private HashMap<String, HashSet<ClientSocket>> rooms;
    private final String defaultRoomName = "default";

    public RoomsPool(HashMap rooms) {
        this.rooms = rooms;
        rooms.put(defaultRoomName, new HashSet<ClientSocket>());
    }

    public boolean addClientToDefaultRoom(ClientSocket clientSocket) {
        synchronized (rooms) {
            return getRoom(defaultRoomName).add(clientSocket);
        }
    }

    public HashSet<ClientSocket> getRoom(String name) {
        if (!rooms.containsKey(name)) {
            rooms.put(name, new HashSet<>());
        }
        return rooms.get(name);
    }

    public boolean moveClientToAnotherRoom(ClientSocket clientSocket, String oldRoom, String newRoom) throws IOException {
        synchronized (rooms) {
//            System.out.println(roomName +"   "+ rooms +"   "+ clientSocket);
            if (!getRoom(oldRoom).contains(clientSocket)) {
                return false;
            }
            getRoom(oldRoom).remove(clientSocket);
            getRoom(newRoom).add(clientSocket);
//            removeClientfromPool(clientSocket);
            checkRoomFullness(oldRoom);
            return true;
        }
    }

    public boolean checkNameAvailibility(String clientName) {
        boolean isValid = true;
        synchronized (rooms) {
            for (Collection room : rooms.values()) {
                if (room.contains(clientName)) {
                    isValid = false;
                    break;
                }
            }
        }
        return isValid;
    }

    public void checkRoomFullness(String roomName) {
        if (getRoom(roomName).isEmpty()){
            rooms.remove(roomName);
        }
    }

    public boolean removeClientfromPool(ClientSocket clientSocket) throws IOException {
        for(Collection room : rooms.values()){
            if(room.contains(clientSocket)){
                clientSocket.close();
                return room.remove(clientSocket);
            }
        }
        return false;
    }
}
